//
// Created by dai on 4/22/21.
//


//#include <stdarg.h>

#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <android/log.h>
#include <unistd.h>
#include "dai_log.h"
#include <fcntl.h>
#include <sys/file.h>
#include <math.h>

const char *tag = "MyLog-Ndk";
const int MAXLINE = 1024;
const char buf[MAXLINE];
void dai_log(const char* fmt,...){
    va_list ap;
    va_start(ap,fmt);
    vsnprintf(buf,MAXLINE,fmt,ap);
    va_end(ap);
    __android_log_print(ANDROID_LOG_ERROR,tag,"%s", buf);
}



float dai_sqrt(float value){
    return sqrtf(value);
}

int counter = 0;
void dai_fork(){
    dai_log("before  fork:");
    pid_t pid = fork();
    if (pid == 0){
        // 子进程
        setsid();
        while (1){
            counter++;
            dai_log("子进程执行.... :%d",counter);
            sleep(1);
        }
    } else{
        dai_log("啦啦啦. 我是父进程.3s后自杀!");
        sleep(3);
        dai_log("准备退出了!");
        exit(1);
        dai_log("11111");
    }
}


void gen_guer_process(){
    pid_t pid;
    if((pid = fork()) < 0){
        dai_log("第一次fork进程失败!");
        exit(1);
    }else if(pid == 0){
        // child
        if((pid = fork()) < 0){
            dai_log("子进程fork失败!");
            exit(2);
        }else if(pid > 0){
            // 托孤
            dai_log("子进程自己退出,进行托孤!");
            exit(0);
        }

        //--------------------
        dai_log("我是孙子进程,我的pid:%ld",getpid());
        int szcount = 0;
        while (1){
            sleep(1);
            szcount++;
            dai_log("szcount:%d, ppid:%ld",szcount,getppid());
        }
    }
}


void p1_do(const char* filepath){

    // fork一个中间进程 中间进程创造一个
    pid_t pid = fork();
    if (pid < 0){
        dai_log("fork 失败!");
        exit(1);
    }else if(pid == 0){
        // 继续fork一个
    }


    // 如果 文件已经被其他锁锁住, 则会阻塞住
    if (lock_file(filepath)){
        dai_log(">> p1 进程 获得文件锁!");

        //
        while (1){
            sleep(1);
        }
    }else{
        dai_log(">> p1 进程 lock_file 失败!");
    }
}
void p2_do(const char* filepath){
    // 如果 文件已经被其他锁锁住, 则会阻塞住
    if (lock_file(filepath)){
        dai_log(">> p2 进程 获得文件锁!");
        while (1){
            sleep(1);
        }
    }else{
        dai_log(">> p2 进程 lock_file 失败!");
    }
}


int lock_file(char *lock_file_path) {
    dai_log("start try to lock file >> %s <<", lock_file_path);
    int lockFileDescriptor = open(lock_file_path, O_RDONLY);
    if (lockFileDescriptor == -1) {
        lockFileDescriptor = open(lock_file_path, O_CREAT, S_IRUSR);
    }
    int lockRet = flock(lockFileDescriptor, LOCK_EX);
    if (lockRet == -1) {
        dai_log("lock file failed >> %s <<", lock_file_path);
        return 0;
    } else {
        dai_log("lock file success  >> %s <<", lock_file_path);
        return 1;
    }
}